using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using Crab.Services.Proxy;
using Crab.Web.Security;

namespace Crab.WorkflowClient
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtPassword.Text) || string.IsNullOrEmpty(this.txtTenantName.Text)
                || string.IsNullOrEmpty(this.txtUserName.Text))
            {
                this.lblErrorMsg.Text = "Please input tenantname,username and password.";

                return;
            }

            if(!AuthenticationProxy.ValidateUser(this.txtTenantName.Text.Trim(), this.txtUserName.Text.Trim(), this.txtPassword.Text.Trim()))
            {
                this.lblErrorMsg.Text = "Login failed.please check your input information.";
                return;
            }
            string adminRoleName = ConfigurationManager.AppSettings["Tenant_Admin_Role"];
            if(!AuthorizationProxy.IsUserInRole(this.txtTenantName.Text.Trim(), this.txtUserName.Text.Trim(), adminRoleName))
            {
                this.lblErrorMsg.Text = "Insufficient privilege!";
                return;
            }

            TenantContext.TenantName = this.txtTenantName.Text.Trim();
            TenantContext.Username = this.txtUserName.Text.Trim();
            TenantContext.Password = this.txtPassword.Text.Trim();

            this.DialogResult = DialogResult.OK;

            this.Close();
        }

        public string TenantId;
        public string UserId;

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;

            this.Close();
        }

        private void txtUserName_KeyPress(object sender, KeyPressEventArgs e)
        {
            this.lblErrorMsg.Text = "";
        }

        private void txtTenantName_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnOK_Click(sender, null);
            }
        }
    }
}